package com.kgc.manager.controller;

import com.kgc.manager.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Controller
public class PicUploadController {

    @Value("${imageServer}")
    private String imageServer;

    //单个文件上传
    @RequestMapping("upload")  //*.jpg  *.png
    @ResponseBody
    public Map uploadFile(@RequestParam("file") MultipartFile file) throws Exception{
        FastDFSClient fastDFSClient=new FastDFSClient("classpath:resources/fdfs_client.conf");
       String fileName=file.getOriginalFilename();
       String ext=fileName.substring(fileName.lastIndexOf(".")+1);
        String path=imageServer+fastDFSClient.uploadFile(file.getBytes(),ext);//
        Map map=new HashMap();
        map.put("path",path);
        return map;
    }

    //处理批量上传
    @RequestMapping("uploadFile")
    @ResponseBody
    public Map uploadFile2(HttpServletRequest request) throws Exception {
        // 创建一个通用的多部分解析器
        Map map=new HashMap();
        FastDFSClient fastDFSClient=new FastDFSClient("classpath:resources/fdfs_client.conf");
        //存储上传成功后文件的地址+文件名
        List<String> list=new ArrayList<String>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // get the parameter names of the multipart files contained in this request
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 取得上传文件
                List<MultipartFile> multipartFiles = multiRequest.getFiles(iter.next());
                for (MultipartFile multipartFile : multipartFiles) {
                    String fileName=multipartFile.getOriginalFilename();
                    String ext=fileName.substring(fileName.lastIndexOf(".")+1);
                    String path=imageServer+fastDFSClient.uploadFile(multipartFile.getBytes(),ext);//
                    list.add(path);
                }
            }
        }
        map.put("code",0);
        map.put("data",list);
        return map;
    }
}
